// 真机震动测试工具 - 专门针对真机环境优化
class RealDeviceVibrate {
  
  // 真机环境检测
  detectRealDevice() {
    console.log('=== 真机环境检测 ===');
    
    // #ifdef APP-PLUS
    try {
      const deviceInfo = uni.getSystemInfoSync();
      console.log('设备信息:', {
        model: deviceInfo.model,
        system: deviceInfo.system,
        platform: deviceInfo.platform,
        brand: deviceInfo.brand
      });
      
      // 检查是否为真机
      const isRealDevice = deviceInfo.platform === 'android' || deviceInfo.platform === 'ios';
      console.log('是否为真机:', isRealDevice);
      
      return {
        isRealDevice,
        deviceInfo
      };
    } catch (error) {
      console.error('设备检测失败:', error);
      return { isRealDevice: false, error: error.message };
    }
    // #endif
    
    // #ifndef APP-PLUS
    console.log('当前不是APP环境');
    return { isRealDevice: false, reason: '非APP环境' };
    // #endif
  }

  // 真机震动权限检查
  checkRealDevicePermission() {
    console.log('=== 真机权限检查 ===');
    
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const PackageManager = plus.android.importClass('android.content.pm.PackageManager');
      
      const permission = 'android.permission.VIBRATE';
      const result = main.checkSelfPermission(permission);
      const hasPermission = result === PackageManager.PERMISSION_GRANTED;
      
      console.log('震动权限状态:', hasPermission ? '已授予' : '未授予');
      
      if (!hasPermission) {
        console.log('尝试请求权限...');
        this.requestPermission();
      }
      
      return hasPermission;
    } catch (error) {
      console.error('权限检查失败:', error);
      return false;
    }
    // #endif
    
    return true;
  }

  // 请求震动权限
  requestPermission() {
    // #ifdef APP-PLUS
    plus.android.requestPermissions(
      ['android.permission.VIBRATE'],
      (result) => {
        console.log('权限请求结果:', result);
        if (result.granted && result.granted.length > 0) {
          uni.showToast({ title: '权限获取成功', icon: 'success' });
        } else {
          uni.showToast({ title: '权限被拒绝', icon: 'none' });
        }
      },
      (error) => {
        console.error('权限请求失败:', error);
        uni.showToast({ title: '权限请求失败', icon: 'none' });
      }
    );
    // #endif
  }

  // 真机震动测试 - 最简单有效的方法
  async testRealDeviceVibrate() {
    console.log('=== 真机震动测试 ===');
    
    const results = [];
    
    // 测试1: uni.vibrateShort (推荐)
    try {
      console.log('测试 uni.vibrateShort...');
      const result1 = await new Promise((resolve) => {
        uni.vibrateShort({
          success: () => {
            console.log('✅ uni.vibrateShort 成功');
            resolve(true);
          },
          fail: (err) => {
            console.log('❌ uni.vibrateShort 失败:', err);
            resolve(false);
          }
        });
      });
      results.push({ method: 'uni.vibrateShort', success: result1 });
    } catch (e) {
      results.push({ method: 'uni.vibrateShort', success: false, error: e.message });
    }

    // 等待1秒
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 测试2: uni.vibrate
    try {
      console.log('测试 uni.vibrate...');
      const result2 = await new Promise((resolve) => {
        uni.vibrate({
          success: () => {
            console.log('✅ uni.vibrate 成功');
            resolve(true);
          },
          fail: (err) => {
            console.log('❌ uni.vibrate 失败:', err);
            resolve(false);
          }
        });
      });
      results.push({ method: 'uni.vibrate', success: result2 });
    } catch (e) {
      results.push({ method: 'uni.vibrate', success: false, error: e.message });
    }

    // 等待1秒
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 测试3: 原生Android震动
    // #ifdef APP-PLUS
    try {
      console.log('测试原生Android震动...');
      const result3 = await this.nativeVibrate();
      results.push({ method: 'native', success: result3 });
    } catch (e) {
      results.push({ method: 'native', success: false, error: e.message });
    }
    // #endif

    console.log('震动测试结果:', results);
    return results;
  }

  // 原生震动实现
  async nativeVibrate() {
    // #ifdef APP-PLUS
    try {
      const main = plus.android.runtimeMainActivity();
      const Context = plus.android.importClass('android.content.Context');
      const Vibrator = plus.android.importClass('android.os.Vibrator');
      
      const vibrator = main.getSystemService(Context.VIBRATOR_SERVICE);
      
      if (vibrator && vibrator.hasVibrator()) {
        vibrator.vibrate(500); // 简单震动500ms
        console.log('✅ 原生震动执行成功');
        return true;
      } else {
        console.log('❌ 设备不支持震动');
        return false;
      }
    } catch (error) {
      console.error('❌ 原生震动失败:', error);
      return false;
    }
    // #endif
    return false;
  }

  // 真机震动问题诊断
  async diagnoseRealDevice() {
    console.log('🔍 开始真机震动诊断...');
    
    const report = {
      device: null,
      permission: false,
      vibrationTests: [],
      suggestions: []
    };

    // 1. 设备检测
    report.device = this.detectRealDevice();
    
    if (!report.device.isRealDevice) {
      report.suggestions.push('请在真机上测试，模拟器不支持震动');
      return report;
    }

    // 2. 权限检查
    report.permission = this.checkRealDevicePermission();
    
    if (!report.permission) {
      report.suggestions.push('震动权限未授予，请允许权限');
    }

    // 3. 震动测试
    report.vibrationTests = await this.testRealDeviceVibrate();
    
    // 4. 生成建议
    const hasSuccess = report.vibrationTests.some(test => test.success);
    
    if (!hasSuccess) {
      report.suggestions.push('所有震动方法都失败，请检查以下设置：');
      report.suggestions.push('1. 手机设置 → 声音和振动 → 触觉反馈 (开启)');
      report.suggestions.push('2. 确保手机不在静音模式');
      report.suggestions.push('3. 关闭省电模式');
      report.suggestions.push('4. 重启应用后再试');
    } else {
      report.suggestions.push('震动功能正常！');
    }

    return report;
  }

  // 显示诊断结果
  showDiagnosticResult(report) {
    let message = '=== 真机震动诊断结果 ===\n\n';
    
    // 设备信息
    if (report.device.isRealDevice) {
      message += `✅ 真机环境: ${report.device.deviceInfo.model}\n`;
    } else {
      message += `❌ 非真机环境: ${report.device.reason || report.device.error}\n`;
    }
    
    // 权限状态
    message += `${report.permission ? '✅' : '❌'} 震动权限: ${report.permission ? '已授予' : '未授予'}\n\n`;
    
    // 测试结果
    message += '震动测试结果:\n';
    report.vibrationTests.forEach(test => {
      message += `${test.success ? '✅' : '❌'} ${test.method}: ${test.success ? '成功' : '失败'}\n`;
    });
    
    // 建议
    if (report.suggestions.length > 0) {
      message += '\n建议:\n';
      report.suggestions.forEach((suggestion, index) => {
        message += `${index + 1}. ${suggestion}\n`;
      });
    }
    
    console.log(message);
    
    // 显示弹窗
    uni.showModal({
      title: '真机震动诊断',
      content: message,
      showCancel: false,
      confirmText: '知道了'
    });
  }
}

export default new RealDeviceVibrate();